package cn.innosmart.aq.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import cn.innosmart.aq.R;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.manager.ContactsManager;
import cn.innosmart.aq.util.UpdateManager;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * 软件设置界面
 * Created by David on 2015/7/27.
 */
public class AppSettingActivity extends BaseActivity {


    private final int EXIT = 0;
    private final int CHECKUPDATE = 1;
    private final int SHOW_DELCARE_ALERT = 222;
    private TextView tv_versionName;
    private RelativeLayout rl_change_background;
    private RelativeLayout rl_app_update;
    private RelativeLayout rl_app_delcare;
    private RelativeLayout rl_about_us;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    //检查APP更新
    private UpdateManager updateManager;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
                case CHECKUPDATE:
                    //检查更新
                    checkUpdate();
                    break;
                case SHOW_DELCARE_ALERT:
                    jsonStatementUrl = new JsonObjectRequest(statementUrl, null,
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d("TAG", response.toString());
                                    showStatementDialog(response);
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.e("TAG", error.getMessage(), error);
                                }
                            });

                    AQApplication.getInstance().mQueue.add(jsonStatementUrl);

                    break;
            }
        }
    };
    //    private  Boolean isShow = false;
    private int clickNum = 1;
    private View.OnClickListener mItemOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_change_background:
                    showToast("开发中");
                    break;
                case R.id.rl_app_update:
//                    mHandler.sendEmptyMessage(CHECKUPDATE);

                    String version = tv_versionName.getText().toString();
                    System.out.println("Version=" + version + "length=" + version.split("\\.").length);
                    if (version.split("\\.").length != 3)
                        showVersion();
                    break;
                case R.id.rl_app_delcare:
                    Intent resourceIntent = new Intent();
                    resourceIntent.setAction("android.intent.action.VIEW");
                    Uri resource_url = Uri.parse("http://www.gangganghao.com.cn/about/detail/?id=73");
                    resourceIntent.setData(resource_url);
                    startActivity(resourceIntent);

                    break;
                case R.id.rl_about_us:
                    showToast("开发中");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_setting);
        setBar();
        initView();
        setListener();
        setData();
    }

    private void setData() {
        tv_versionName.setText(getVersion(0));
    }

    private JsonObjectRequest jsonStatementUrl;

    private String statementUrl = "http://fwupgrade.gangganghao.com.cn/download_aq_01/statement.json";

    public void AppExit() {

        this.finish();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

/*int pid = android.os.Process.myPid();=====> use this if you want to kill your activity. But its not a good one to do.
 android.os.Process.killProcess(pid);*/

    }


    private void showStatementDialog(JSONObject statementObject) {
        String statement;
        try {
            ContactsManager cm = new ContactsManager(this.getContentResolver());
            String lang = Locale.getDefault().toString();

            statement = statementObject.getString(lang);
            LayoutInflater inflater = LayoutInflater.from(this);
            View view = inflater.inflate(R.layout.declare_dialog, null);
            TextView textview = (TextView) view.findViewById(R.id.textmsg);
            textview.setText(statement);
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.setTitle(R.string.app_declare);
            alertDialog.setView(view);
            alertDialog.setNegativeButton(R.string.not_agree, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    AppExit();
                }
            });
            alertDialog.setPositiveButton(R.string.agree, null);
            AlertDialog alert = alertDialog.create();
            alert.show();

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    private void setListener() {
        rl_change_background.setOnClickListener(mItemOnClickListener);
        rl_app_update.setOnClickListener(mItemOnClickListener);
        rl_app_delcare.setOnClickListener(mItemOnClickListener);
        rl_about_us.setOnClickListener(mItemOnClickListener);
    }

    private void initView() {
        tv_versionName = (TextView) findViewById(R.id.tv_versionName);
        rl_change_background = (RelativeLayout) findViewById(R.id.rl_change_background);
        rl_app_update = (RelativeLayout) findViewById(R.id.rl_app_update);
        rl_app_delcare = (RelativeLayout) findViewById(R.id.rl_app_delcare);
        rl_about_us = (RelativeLayout) findViewById(R.id.rl_about_us);
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_app_setting));
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    private void checkUpdate() {
        updateManager = new UpdateManager(AppSettingActivity.this);
        updateManager.geUpdateInfo(2);
    }

    /**
     * 根据type
     * 获取当前app的不同格式的版本号   0为 2位版本号  1为3位版本号
     *
     * @param type
     * @return
     */
    public String getVersion(int type) {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            if (type == 0) {
                int index = version.lastIndexOf(".");
                version = version.substring(0, index);
            } else if (type == 1) {

            }
            return getString(R.string.version_name) + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "UnKnown";
        }
    }

    private void showVersion() {
        Timer tExit = null;
        TimerTask task = null;
        if (clickNum != 3) {
            clickNum++; // 准备退出
//            Toast.makeText(this, "再按" + (3 - clickNum + 1) + "下，显示完整版本号!", Toast.LENGTH_SHORT).show();
            if (tExit != null) {
                tExit.cancel();
                tExit = null;
            }
            if (task != null) {
                task.cancel();
                task = null;
            }
            task = new TimerTask() {
                @Override
                public void run() {
                    clickNum = 0; // 取消显示
                }
            };
            tExit = new Timer();
            tExit.schedule(task, 2000); // 如果2秒钟内没有按下，则启动定时器取消掉刚才执行的任务
        } else {
            tv_versionName.setText(getVersion(1));
        }
    }


}
